import { app } from "../app";
import { msgId } from "../cfg/msgcfg";

let uid = 1;
let players: Player[] = [];
let playerDic: { [uid: number]: Player } = {};

export class Player {

    uid: number
    sid: string
    roomId: number
    name: string

    constructor(uid: number, sid: string, name: string) {
        this.uid = uid;
        this.sid = sid;
        this.name = name;
    }

}

export class Room {

    id: number;
    players: Player[] = [];
    playerDic: { [uid: number]: Player } = {};
    chats: string[] = [];

    constructor(id: number) {
        this.id = id;
    }

    join(uid: number) {
        let player = playerDic[uid];
        if (player && !this.playerDic[uid]) {
            let chat = `${player.name}加入了房间！`;
            this.chats.push(chat);
            this.boardcast(msgId.chat, { chat, onlineCount: this.players.length + 1 });
            player.roomId = this.id;
            this.players.push(player);
            this.playerDic[player.uid] = player;
        }
    }

    exit(uid: number) {
        let player = this.playerDic[uid];
        if (player) {
            player.roomId = null;
            this.players.splice(this.players.indexOf(player), 1);
            delete this.playerDic[uid];
            let chat = `${player.name}离开了房间！`;
            this.chats.push(chat);
            this.boardcast(msgId.chat, { chat, onlineCount: this.players.length });
        }
    }

    chat(uid: number, str: string) {
        let player = this.playerDic[uid];
        if (player) {
            let date = new Date();
            let dateStr = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
            let chat = `[${dateStr}](${player.name}): ${str}`;
            this.chats.push(chat);
            this.boardcast(msgId.chat, { chat });
        }
    }

    boardcast(msgId: number, msg?: any) {
        let sidUids: { [sid: string]: number[] } = {};
        this.players.forEach(player => {
            sidUids[player.sid] ||= [];
            sidUids[player.sid].push(player.uid);
        })
        app.backendSvr.boardcast(sidUids, msgId, msg);
    }

}

let roomDic: { [id: number]: Room } = {
    1: new Room(1),
    2: new Room(2)
};

export function joinGame(sid: string, name: string) {
    let player = new Player(uid++, sid, name);
    players.push(player);
    playerDic[player.uid] = player;
    return player.uid;
}

export function exitGame(uid: number) {
    let player = getPlayer(uid);
    if (player) {
        getRoom(player.roomId).exit(uid);
        players.slice(players.indexOf(player), 1);
        delete playerDic[uid];
    }
}

export function getPlayer(uid: number) {
    return playerDic[uid];
}

export function getRoom(id: number) {
    return roomDic[id];
}

export function getRoomIds() {
    let ids: number[] = [];
    for (let key in roomDic) {
        ids.push(Number(key));
    }
    return ids;
}